package com.tensquare.article.controller;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.plugins.Page;
import com.tensquare.article.feign.NoticeFeignClient;
import com.tensquare.article.pojo.Article;
import com.tensquare.article.pojo.Notice;
import com.tensquare.article.service.ArticleService;
import com.tensquare.entity.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import java.util.Date;
import java.util.Map;
import java.util.Set;

/**
 * @author BAO
 * @version V1.0
 * @Package com.tensquare.article.controller
 * @date 2020/12/2 21:07
 * @description:
 */
@CrossOrigin
@RestController
@RequestMapping("/article")
public class ArticleController {
    @Autowired
    private ArticleService articleService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private NoticeFeignClient noticeFeignClient;

    @GetMapping("/findAll")
    public Result findAll(){
        Page<Article> page = articleService.findAll();
        return Result.success("success", page);
    }

    @GetMapping("/findById/{id}")
    public Result findById(@PathVariable("id") String id){
        Article article = articleService.findById(id);
        return Result.success("success",article);
    }

    @PostMapping("/add")
    public Result add(@RequestBody Article article){
        //雪花算法生成id
        Snowflake snowflake = IdUtil.createSnowflake(0, 1);
        long id = snowflake.nextId();
        article.setId(String.valueOf(id));
        //初始化数据
        article.setVisits(0);   //浏览量
        article.setThumbup(0);  //点赞数
        article.setComment(0);  //评论数
        //新增
        int i = articleService.add(article);

        //TODO 使用jwt获取当前用户的userid，也就是文章作者的id
        String authorId = "3";
        //获取需要通知的读者
        String authorKey = "article_author_" + authorId;
        Set<String> members = redisTemplate.boundSetOps(authorKey).members();
        members.forEach(member->{
            //消息通知
            Notice notice = new Notice();
            notice.setReceiverId(member);
            notice.setOperatorId(authorId);
            notice.setAction("publish");
            notice.setTargetType("article");
            notice.setTargetId(String.valueOf(id));
            notice.setCreatetime(new Date());
            notice.setType("sys");
            notice.setState("0");
            noticeFeignClient.add(notice);
        });
        return i>0?Result.success("success",null):Result.fail("fail");
    }
    
    @PutMapping("/update")
    public Result update(@RequestBody Article article){
        int update = articleService.update(article);
        return update>0?Result.success("success",null):Result.fail("fail");
    }

    @DeleteMapping("/deleteById/{id}")
    public Result deleteById(@PathVariable("id") String id){
        int i = articleService.deleteById(id);
        return i>0?Result.success("success",null):Result.fail("fail");
    }

    @PostMapping("/pageSearch/{currentPage}/{size}")
    public Result pageSearch(@RequestBody Map map ,
                             @PathVariable("currentPage") Integer currentPage,
                             @PathVariable("size") Integer size){
        Page<Article> page = articleService.pageSearch(map, currentPage, size);
        return Result.success("success",page);
    }

    @PutMapping("/thumbup/{id}")
    public Result thumbup(@PathVariable("id") String articleId){
        //模拟用户id
        String userId = "4";
        String key = "thumbup_article_" + userId + "_" + articleId;
        //查询用户点赞信息，根据用户id和文章id
        Object flag  = redisTemplate.opsForValue().get(key);
        //判断查询到的结果是否为空
        if (flag!=null){
            //如果为空，表示用户没有点过赞，可以点赞
            articleService.thumbup(articleId);
            //点赞成功，保存点赞信息
            redisTemplate.opsForValue().set(key, 1);
            return Result.success("点赞成功",null);
        }

        return Result.fail("请不要重复点赞");

    }

}
